from flask import g,request
from flask_restful import Resource
from sqlalchemy.dialects.mysql import insert
from sqlalchemy.orm import load_only
from models import db
from models.article import Channel, UserChannel
from utils.decorators import login_required

"""用户频道"""
class UserChannelResource(Resource):

    method_decorators = {'put': [login_required]}

    def get(self):
        # 获取用户信息
        userid = g.userid

        if userid:  # 判断用户已登录, 查询用户频道
            # 查询用户的频道
            channels = Channel.query.options(load_only(Channel.id, Channel.name)).join(UserChannel,
                                            Channel.id == UserChannel.channel_id).filter(UserChannel.user_id == userid,
                                                                                         UserChannel.is_deleted == False).order_by(UserChannel.sequence).all()
            if len(channels) == 0:  # 用户没有选择频道, 查询默认频道
                channels = Channel.query.options(load_only(Channel.id, Channel.name)).filter(
                    Channel.is_default == True).all()
        else:  # 用户未登录, 查询默认频道
            channels = Channel.query.options(load_only(Channel.id, Channel.name)).filter(Channel.is_default == True).all()

        # 序列化
        channel_list = [channel.to_dict() for channel in channels]
        channel_list.insert(0, {'id': 0, 'name': '推荐'})

        return {'channels': channel_list}

    """修改用户频道  重置式更新"""
    def put(self):
        # 获取参数
        userid = g.userid
        channels = request.json.get('channels')

        # 将现有的用户频道列表全部删除
        UserChannel.query.filter(UserChannel.user_id == userid, UserChannel.is_deleted == False).update({'is_deleted': True})

        """使用mysql的优化语法  一句批量插入&更新"""
        insert_stmt = insert(UserChannel).values([{'user_id': userid, 'channel_id': channel['id'],
                                                   'sequence': channel['seq']} for channel in channels])
        update_stmt = insert_stmt.on_duplicate_key_update(is_deleted=False, sequence=insert_stmt.inserted.sequence)

        db.session.execute(update_stmt)
        db.session.commit()

        return {'channels': channels}